using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XProject.Entity;
using XProject.DAO;
using XProject.Util;
using System.Configuration;
namespace XProject.GUI
{
    public partial class EventManager : Form
    {
        EventDAO daoEvent = new EventDAO();
        EventTypeDAO daoEventType = new EventTypeDAO();
        IList<Event> events = null;
        public EventManager()
        {
            InitializeComponent();
        }
        public void AddListItem(Event e)
        {
            ListViewItem item = new ListViewItem(e.StartTime.ToShortDateString());
            item.SubItems.Add(e.LunarDay.ToString()+"/"+e.LunarMonth.ToString());
            item.SubItems.Add(e.StartTime.ToShortTimeString());
            item.SubItems.Add(e.Content);
                item.Tag=e;
                lsvEvents.Items.Add(item);

        }
     

        private void EventManager_Load(object sender, EventArgs e)
        {           
          //set icon
           // string icon = Application.StartupPath + "\\" + ConfigurationManager.AppSettings["icon"];
           // if (System.IO.File.Exists(icon)) { this.Icon = new Icon(icon); }
            //load data

            IList<EventType> eventTypes = daoEventType.GetAllType();
            if (eventTypes.Count > 0)
            {
                foreach (EventType etype in eventTypes)
                {
                    ListItem cmiEventType = new ListItem(etype.TypeName,etype);
                    cmbEventType.Items.Add(cmiEventType);
                }
                //cmbEventType.SelectedIndex = 0;
            }
          //  if (events.Count > 0)
           //     foreach (Event ev in events) AddListItem(ev);
            dmnPriority.SelectedIndex = 2;
            cmbViewMode.SelectedIndex = 0;
        }

        private void radSolar_CheckedChanged(object sender, EventArgs e)
        {
            mskLunarDate.Enabled = false;
            dtpEndTime.Enabled = true;
            dtpStartTime.Enabled = true;
        }

        private void radLunar_CheckedChanged(object sender, EventArgs e)
        {
            mskLunarDate.Enabled = true;
            dtpEndTime.Enabled = false;
            dtpStartTime.Enabled = false;
        }
        /// <summary>
        /// Update the selected event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (lsvEvents.SelectedIndices.Count == 0)
            {
                MessageBox.Show("Please select an event");
                return;
            }
            Event ev = lsvEvents.SelectedItems[0].Tag as Event;
            ev.StartTime = dtpStartTime.Value;
            ev.EndTime = dtpEndTime.Value;
            ev.LunarDay = mskLunarDate.LunarDay;
            ev.LunarMonth = mskLunarDate.LunarMonth;
            ev.Content = txtContent.Text;
            ev.Note = txtNote.Text;
            ev.Place = txtPlace.Text;
            ev.IsPublic = chkPublic.Checked;
            ev.Priority = (byte)(dmnPriority.SelectedIndex+1);
            ListItem cmiEType = cmbEventType.SelectedItem as ListItem;
            ev.Type = cmiEType.Tag as EventType;
            if (daoEvent.Update(ev) > 0)
            {
                MessageBox.Show("Updated sucessfully");
                lsvEvents.SelectedItems[0].Text = ev.StartTime.ToShortDateString();
                lsvEvents.SelectedItems[0].SubItems[1].Text = ev.LunarDay.ToString() + "/" + ev.LunarMonth.ToString();
                lsvEvents.SelectedItems[0].SubItems[2].Text = ev.StartTime.ToShortTimeString();
                lsvEvents.SelectedItems[0].SubItems[3].Text = ev.Content;
                if(!events.Contains(ev))
                events.Add(ev);
            }
            else MessageBox.Show(daoEvent.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
        }
        /// <summary>
        /// Add an event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (!IsValidInput()) return;
            Event ev = new Event();
            ev.Account.AccountID = MainForm.CurrentAccount.AccountID;
            ev.StartTime = dtpStartTime.Value;
            ev.EndTime = dtpEndTime.Value;
            ev.LunarDay = mskLunarDate.LunarDay;
            ev.LunarMonth = mskLunarDate.LunarMonth;
            ev.Content = txtContent.Text;
            ev.Place = txtPlace.Text;
            ev.Priority = (byte)(dmnPriority.SelectedIndex + 1);
            ev.Note = txtNote.Text;
            ev.IsPublic = chkPublic.Checked;
            ListItem cmiEType = cmbEventType.SelectedItem as ListItem;
            ev.Type = cmiEType.Tag as EventType;
            if (daoEvent.Insert(ev) > 0)
            {
                MessageBox.Show("Added successfully");
                AddListItem(ev);
                events.Remove(ev);
                events.Add(ev);
                txtContent.Text = "";
                txtPlace.Text = "";
                txtNote.Text = "";               
            }
            else MessageBox.Show(daoEvent.Message);
            
        }
        /// <summary>
        /// check if the required field is valid
        /// </summary>
        /// <returns></returns>
        public bool IsValidInput()
        {
            if (txtContent.Text == "")
            {
                MessageBox.Show("Content must not be empty");
                txtContent.Focus();
                return false;
            }
            else
            if (cmbEventType.SelectedItem == null)
            {
                MessageBox.Show("Please choose type of the event");
                cmbEventType.Focus();
                return false;
            }
            else if (radLunar.Checked && mskLunarDate.Text.Length < 3)
            {
                MessageBox.Show("Please input valid lunar date value");
                mskLunarDate.Focus();
                return false;
            }
        return true;

        }
        /// <summary>
        /// Delete selected event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lsvEvents.SelectedIndices.Count < 0)
            { MessageBox.Show("Please select a event");
            return;
            }
            if (MessageBox.Show("Are you sure want to delete this event?","Confirm",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2) != DialogResult.Yes) return;
                Event ev = lsvEvents.SelectedItems[0].Tag as Event;
                if (daoEvent.Delete(ev) > 0)
                {
                    MessageBox.Show("The event has just been deleted successfully");
                    lsvEvents.Items.Remove(lsvEvents.SelectedItems[0]);
                    events.Remove(ev);
                }
                else MessageBox.Show(daoEvent.Message);

            }

        private void cmbViewMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            lsvEvents.Items.Clear();
            
            if(cmbViewMode.SelectedIndex==0)
             events = daoEvent.GetEventByPeriodOfTime(MainForm.CurrentAccount.AccountID, Util.CalendarCalulator.GetFisrtDayOfWeek(DateTime.Today), Util.CalendarCalulator.GetLastDayOfWeek(DateTime.Today));//set accountID here
            else if(cmbViewMode.SelectedIndex==1)
             events = daoEvent.GetEventByPeriodOfTime(MainForm.CurrentAccount.AccountID, Util.CalendarCalulator.GetFirstDayOfMonth(DateTime.Today), Util.CalendarCalulator.GetLastDayOfMonth(DateTime.Today));//set accountID here
            else if (cmbViewMode.SelectedIndex == 2)
            {
                if (cmbEventType.SelectedIndex != -1)
                {
                    ListItem cmiEType = cmbEventType.SelectedItem as ListItem;
                    EventType type = cmiEType.Tag as EventType;
                    events = daoEvent.GetEventByType(MainForm.CurrentAccount.AccountID, type);//set account id here
                }
            }
            
            if (events!=null)
                foreach (Event ev in events) AddListItem(ev);
        }

        private void cmbEventType_SelectedIndexChanged(object sender, EventArgs e)
        {            
            
            if (cmbEventType.SelectedIndex != -1 && cmbViewMode.SelectedIndex==2)
            {
                 IList<Event> events = null;
                lsvEvents.Items.Clear();
                ListItem cmiEType = cmbEventType.SelectedItem as ListItem;
                EventType type = cmiEType.Tag as EventType;
                events = daoEvent.GetEventByType(MainForm.CurrentAccount.AccountID, type); //set accountid here
                if (events != null)
                foreach (Event ev in events) AddListItem(ev);
            }            
        }

        private void lsvEvents_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lsvEvents.SelectedItems.Count > 0)
            {
                Event ev = lsvEvents.SelectedItems[0].Tag as Event;
                dtpStartTime.Value = ev.StartTime;
                dtpEndTime.Value = ev.EndTime;
                txtContent.Text = ev.Content;
                txtPlace.Text = ev.Place;
                chkPublic.Checked = ev.IsPublic;
                dmnPriority.SelectedIndex = ev.Priority - 1;
                mskLunarDate.Text = ev.LunarDay.ToString() + "/" + ev.LunarMonth.ToString();
                foreach (ListItem cmiEType in cmbEventType.Items)
                {
                    EventType etype = cmiEType.Tag as EventType;
                    if (ev.Type.TypeID == etype.TypeID)
                    {
                        cmbEventType.SelectedItem = cmiEType;
                        break;
                    }
                }
            }
        }

        private void chkPublic_CheckedChanged(object sender, EventArgs e)
        {
            if (chkPublic.Checked) chkPublic.Text = "Yes";
            else chkPublic.Text = "No";
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {                 
            lsvEvents.Items.Clear();
            string keyword=txtSearch.Text;
            foreach (Event ev in events)
            {
                if (ev.Content.Contains(keyword))
                {
                    AddListItem(ev);
                }
            }
        }

        private void dtpStartTime_ValueChanged(object sender, EventArgs e)
        {
            if (dtpEndTime.Value < dtpStartTime.Value) dtpEndTime.Value = dtpStartTime.Value;
        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                lsvEvents.Items.Clear();
                string keyword = txtSearch.Text;
                foreach (Event ev in events)
                {
                    if (ev.Content.Contains(keyword))
                    {
                        AddListItem(ev);
                    }
                }
            }
        }

        private void btnMore_Click(object sender, EventArgs e)
        {
            EventXMLIE eventIE = new EventXMLIE();
            //SaveFileDialog dlgSave = new SaveFileDialog();
            IList<Entity.Event> list = new List<Entity.Event>();
            //int count = 0;
            //foreach (ListViewItem item in lsvEvents.Items)
            //{
            //    if (item.Checked)
            //    {
            //        Entity.Event ev = item.Tag as Event;
            //        if (ev != null) list.Add(ev);
            //    }
            //}
            //dlgSave.DefaultExt = "xml";
            //dlgSave.Filter = "XML files (*.xml)|*.xml";
            //if (dlgSave.ShowDialog() == DialogResult.OK)
            //{
            //    if (list.Count > 0)
            //    {
            //        count = eventIE.Export(list, dlgSave.FileName);
            //    }
            //}
            //MessageBox.Show(string.Format("{0} items are exported", count));

            OpenFileDialog dlgOpen = new OpenFileDialog();
            if (dlgOpen.ShowDialog() == DialogResult.OK)
            {
                list = eventIE.Import(dlgOpen.FileName);
                foreach (Entity.Event ev in list)
                {
                    AddListItem(ev);
                }
            }
        }
    }
}